import React, { useState, useEffect } from "react";
import marked from "marked";
import {
  Row,
  Col,
  Input,
  Select,
  Button,
  Breadcrumb,
  message,
} from "antd";
import "./addarticle.css";
import { Link } from "react-router-dom";

import {
  _addBlog,
  _blogTypeList,
  _updateBlog,
} from "../../util/api/blog/index";
const { Option } = Select;
const { TextArea } = Input;

function AddArticle(props) {
  const [articleId, setArticleId] = useState(0); // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [user_id, setUser_id] = useState(); // 
  const [articleTitle, setArticleTitle] = useState(""); //文章标题
  const [articleContent, setArticleContent] = useState(""); //markdown的编辑内容
  const [markdownContent, setMarkdownContent] = useState("预览内容"); //html内容
  const [typeInfo, setTypeInfo] = useState([]); // 文章类别信息
  const [selectedType, setSelectType] = useState(); //选择的文章类别

  useEffect(() => {
    getData();
    let c_user = JSON.parse(localStorage.getItem("c_user")); 
    setUser_id(c_user.user_id)
    if(props.location.state){
      getArticle()
    }
  }, []);
  marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
  });
  const changeContent = (e) => {
    setArticleContent(e.target.value);
    let html = marked(e.target.value);
    setMarkdownContent(html);
  };
  const getData = () => {
    _blogTypeList()
      .then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          setTypeInfo(res.data.data);
        }
      })
      .catch(() => {
        message.error("服务器错误");
      });
  };
  //选择类别后的便哈
  const selectTypeHandler = (value) => {
    setSelectType(value);
  };
  const saveArticle = () => {
    // markedContent();

    if (!selectedType) {
      message.error("必须选择文章类别");
      return false;
    } else if (!articleTitle) {
      message.error("文章名称不能为空");
      return false;
    } else if (!articleContent) {
      message.error("文章内容不能为空");
      return false;
    } 

    let dataProps = {}; //传递到接口的参数
    dataProps.user_id = user_id
    dataProps.blog_title = articleTitle;
    dataProps.blog_content = articleContent;
    dataProps.content_type_id = selectedType;
    dataProps.blog_time = new Date().getTime();
    dataProps.isadmin = 0

    if(articleId === 0){
      console.log(dataProps);
      _addBlog(dataProps).then((res) => {
        if(res.status === 200 && res.data.code === 0){
          setArticleId(res.data.data.id);
          message.success('文章添加成功',1.3).then(() =>{
            props.history.push("/m/myblog");
          })

        }
      })
    }else{
      let id = articleId
      console.log(dataProps);
      _updateBlog(id,dataProps).then((res) => {
        if (res.status === 200 && res.data.code === 0) {
          message.success("文章修改成功",1.3).then(() =>{
            window.history.back()
          });
        }
      })
    }

  };
  const getArticle = () => {
    let data = props.location.state
    if(data){
      setArticleId(data.blog_id)
      setArticleTitle(data.blog_title)
      setArticleContent(data.blog_content)
      setMarkdownContent(marked(data.blog_content))
      setSelectType(data.content_type_id)
    }
  }
  return (
    <div>
      <Breadcrumb style={{ margin: "16px 0" }}>
        <Breadcrumb.Item>
          <Link to="/m/index">首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/m/myblog"> 我的博客</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>工作台</Breadcrumb.Item>
      </Breadcrumb>
      <div className="admin-body" style={{ padding: 24, minHeight: 360 }}>
        <Row gutter={5}>
          <Col span={24}>
            <Row gutter={10}>
              <Col span={12}>
                <Input
                  placeholder="博客标题"
                  size="large"
                  value={articleTitle}
                  onChange={(e) => {
                    setArticleTitle(e.target.value);
                  }}
                />
              </Col>
              <Col span={4}>
                <Select
                  size="large"
                  placeholder="文章类型"
                  onChange={selectTypeHandler}
                  defaultValue={setSelectType}
                >
                  {typeInfo.map((v) => (
                    <Option value={v.content_type_id}>
                      {v.content_type_name}
                    </Option>
                  ))}
                </Select>
              </Col>
              <Col span={4}></Col>
              <Col span={4}>
                <Button type="primary" size="large" onClick={saveArticle} block>
                  发布文章
                </Button>
              </Col>
            </Row>
            <br />
            <Row gutter={10}>
              <Col span={12}>
                <TextArea
                  className="markdown-content"
                  rows={35}
                  placeholder="博客内容"
                  value={articleContent}
                  onChange={changeContent}
                />
              </Col>
              <Col span={12}>
                <div
                  className="show-html"
                  dangerouslySetInnerHTML={{ __html: markdownContent }}
                ></div>
              </Col>
            </Row>
          </Col>
        </Row>
      </div>
    </div>
  );
}

export default AddArticle;
